<template>
  <div class="callCenterInfos">
    <TitleName
      v-if="!paramData.isDetail"
      class="title"
      icon="i-carbon-bookmark-filled"
      title="短信信息"
    ></TitleName>
    <div v-if="!paramData.isDetail" class="textMessage-Btn">
      <el-button v-if="setRoles" type="primary" @click="setTemplate"
        >设置模版</el-button
      >
      <el-button :loading="sendBtnLoading" type="primary" @click="sendSMSFn"
        >发送短信</el-button
      >
    </div>
    <!-- 基本信息 -->
    <el-form
      v-if="!paramData.isDetail"
      ref="form"
      :model="formData"
      class="callCenterInfos-form mb-20px"
      label-position="right"
      label-width="160px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="formData.customerName"
              disabled
              maxlength="50"
              placeholder="请输入客户名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="telephone">
            <el-input
              v-model="formData.telephone"
              clearable
              maxlength="11"
              placeholder="请输入客户电话"
              type="tel"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员费到期时间" prop="expirationDate">
            <el-date-picker
              v-model="formData.expirationDate"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择会员费到期时间"
              style="width: 100%"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="reservationDateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模板" prop="textTemplatename">
            <el-select
              v-model="formData.textTemplatename"
              :popper-class="'callCenterInfos-form-select'"
              placeholder="请选择模板"
              style="width: 100%"
              @change="textTemplateChange"
            >
              <el-option
                v-for="(dict, index) in textTemplateList"
                :key="index"
                :label="dict.name"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="金额" prop="money">
            <el-input
              v-model="formData.money"
              clearable
              maxlength="20"
              placeholder="请输入金额"
              @blur="moneyBlur('money')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="微信账号" prop="wechat">
            <el-input
              v-model="formData.wechat"
              clearable
              maxlength="50"
              placeholder="请输入微信账号"
              @blur="moneyBlur('wechat')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="银行账号" prop="bankAccount">
            <el-select
              v-model="formData.bankAccount"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择银行账号"
              style="width: 100%"
              @change="bankAccountChange"
            >
              <el-option
                v-for="(dict, index) in bank_account"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="styleHtml">
          <el-form-item v-if="isCustom == 0" label="发送预览" prop="content">
            <div class="pl-10px pb-10px styleHtml-cnt">
              <div v-html="formData.content"></div>
            </div>
          </el-form-item>
          <el-form-item v-else label="发送预览" prop="content">
            <el-input
              v-model="formData.content"
              :autosize="{ minRows: 5, maxRows: 10 }"
              maxlength="500"
              minlength="200"
              placeholder="请输入发送内容"
              type="textarea"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <TitleName
      class="title mb-20px"
      icon="i-carbon-bookmark-filled"
      title="短信历史记录"
    ></TitleName>
    <el-table :data="tableList" border>
      <el-table-column label="发送时间" prop="sendTime" width="140" />
      <el-table-column label="发送人" prop="userName" width="100" />
      <el-table-column label="客户电话" prop="telephone" width="150" />
      <el-table-column
        :show-overflow-tooltip="true"
        label="客户名称"
        prop="customerName"
        width="120"
      >
      </el-table-column>
      <el-table-column
        label="会员费到期时间"
        prop="expirationDate"
        width="170"
      />
      <el-table-column label="银行账号" prop="bankAccount" width="180" />
      <el-table-column label="短信内容" prop="content">
        <template #default="scoped">
          <div v-html="scoped.row.content"></div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="searchFrom.pageSize"
      v-model:page="searchFrom.pageNum"
      :total="total"
      @pagination="getList"
    />
    <!--      设置模块-->
    <el-dialog v-model="templateVisible" title="设置模版" width="600px">
      <el-form
        :label-position="'right'"
        :model="templateform"
        class="setForm-fontsize"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="id">
          <el-select
            v-model="templateform.id"
            :popper-class="'callCenterInfos-form-select'"
            placeholder="请选择模板名称"
            style="width: 100%"
            @change="templateNameChange"
          >
            <el-option
              v-for="(dict, index) in textTemplateList"
              :key="index"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="templateform.content"
            :autosize="{ minRows: 5, maxRows: 10 }"
            maxlength="500"
            minlength="200"
            placeholder="请输入模板内容"
            type="textarea"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer text-right">
          <el-button @click="templateVisible = false">取 消</el-button>
          <el-button
            :loading="saveBtnLoading"
            type="primary"
            @click="templateSaveFn"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="PRStextMessage" setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import { validatePhone } from '@/utils/validate'
import {
  sendSms,
  templateList,
  templateDetail,
  templateSave,
  smsList
} from '@/api/callCenter'
const userStore = useUserStore()
const commonStore = useCommonStore()
const { bank_account } = proxy.useDict('bank_account')
// 接受父级传递的参数
const props = defineProps({
  paramData: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})

const data = reactive({
  formData: {
    content: '',
    bankAccount: '',
    textTemplatename: '',
    money: ''
  },
  templateVisible: false,
  templateform: {
    content: '',
    telephone: '',
    bankAccount: '',
    textTemplatename: ''
  },
  searchFrom: {
    pageSize: 10,
    pageNum: 1
  },
  total: 0,
  tableList: [],
  textTemplateList: [] //短信模板列表
})
const {
  formData,
  templateVisible,
  templateform,
  searchFrom,
  total,
  tableList,
  textTemplateList
} = toRefs(data)
/**根据权限判断是否有设置模板权限（默认 “设置模板”按钮不可见）**/
const setRoles = computed(() => {
  return (
    userStore.roles.includes('sms_template') ||
    userStore.roles.includes('admin')
  )
})
/******相关列表数据**/
//获取短信模版列表
const getTemplateList = () => {
  //获取短信模版列表
  templateList({ pageSize: 9999, pageNum: 1 }).then(e => {
    textTemplateList.value = e.rows
  })
}
function getList() {
  //短信历史记录
  smsList({
    businessId: props.paramData.customerId,
    pageSize: searchFrom.value.pageSize,
    pageNum: searchFrom.value.pageNum
  }).then(res => {
    total.value = res.total
    tableList.value = res.rows
  })
}

/***************************************设置模块***/
//设置模块
const setTemplate = () => {
  templateVisible.value = true
  templateform.value.id =
    textTemplateList.value && textTemplateList.value.length > 0
      ? textTemplateList.value[0].id
      : ''
  templateform.value.content =
    textTemplateList.value && textTemplateList.value.length > 0
      ? textTemplateList.value[0].content
      : ''
  templateform.value.name =
    textTemplateList.value && textTemplateList.value.length > 0
      ? textTemplateList.value[0].name
      : ''
}
//模版名称选中
const templateNameChange = val => {
  templateDetail(val).then(res => {
    console.log(res.data.content, '= res.data.content==')
    templateform.value.content = res.data.content
    templateform.value.name = res.data.name
  })
}
const saveBtnLoading = ref(false)
//保存
const templateSaveFn = () => {
  if (!templateform.value.content) {
    proxy.$modal.msgWarning('模版内容不能为空')
    return false
  }
  saveBtnLoading.value = true
  templateSave(templateform.value)
    .then(res => {
      getTemplateList()
      proxy.$modal.msgSuccess('设置模版成功')
      templateVisible.value = false
    })
    .finally(e => {
      saveBtnLoading.value = false
    })
}
/****************************************发送短信***/
// 金额鼠标移开事件
const moneyBlur = e => {
  if (e == 'wechat') {
    //微信账号
    let text = JSON.parse(JSON.stringify(formData.value.content))
    if (text) {
      formData.value.content = replaceText(text, text.indexOf('WX') != '-1')
    }
    return false
  }
  let reg = /^(\$|￥)?([1-9]\d{0,2}(,\d{3})*|0)(\.\d{1,8})?$/
  if (formData.value.money) {
    if (!reg.test(formData.value.money)) {
      proxy.$modal.msgWarning('请输入正确的金额格式')
      return false
    }
    let text = JSON.parse(JSON.stringify(formData.value.content))
    if (text) {
      formData.value.content = replaceText(text, text.indexOf('JE') != '-1')
    }
  }
}
//替换短信内容
/*
 * isCapsCase  是否是大写字母
 * */
const replaceText = (text, isCapsCase) => {
  console.log(text, isCapsCase, 'isCapsCase---')
  if (isCapsCase) {
    console.log('是大写')
    return text
      .replaceAll(/\n/g, '</br>')
      .replace(
        'KHMC',
        formData.value.customerName
          ? '<span class="khmc" style="color: #aaa; word-break: break-all;">' +
              formData.value.customerName +
              '</span>'
          : 'KHMC'
      )
      .replace(
        'WX',
        formData.value.wechat
          ? '<span class="wx" style="color: #aaa; word-break: break-all;">' +
              formData.value.wechat +
              '</span>'
          : 'WX'
      )
      .replace(
        'JE',
        formData.value.money
          ? '<span class="je" style="color: #aaa; word-break: break-all;">' +
              (formData.value.money ? formData.value.money : '') +
              '</span>'
          : 'JE'
      )
      .replace(
        'HYFDQSJ',
        formData.value.expirationDate
          ? '<span class="hyfdqsj" style="color: #aaa;    word-break: break-all;">' +
              formData.value.expirationDate +
              '</span>'
          : 'HYFDQSJ'
      )
      .replace(
        'YHZH',
        formData.value.bankAccount
          ? '<span class="yhzh" style="color: #aaa;    word-break: break-all;">' +
              formData.value.bankAccount +
              '</span>'
          : 'YHZH'
      )
  } else {
    // 使用 DOMParser 解析 HTML
    const parser = new DOMParser()
    const doc = parser.parseFromString(text, 'text/html')
    console.log(doc, 'doc--小写')
    let hyfdqsj_s = doc.querySelectorAll('span.hyfdqsj')
    hyfdqsj_s.forEach(function (element) {
      element.innerHTML = formData.value.expirationDate
    })
    let yhzh_s = doc.querySelectorAll('span.yhzh')
    yhzh_s.forEach(function (element) {
      element.innerHTML = formData.value.bankAccount
    })
    let khmc_s = doc.querySelectorAll('span.khmc')
    khmc_s.forEach(function (element) {
      element.innerHTML = formData.value.customerName
    })
    let je_s = doc.querySelectorAll('span.je')
    je_s.forEach(function (element) {
      element.innerHTML = formData.value.money
    })
    let wx_s = doc.querySelectorAll('span.wx')
    wx_s.forEach(function (element) {
      element.innerHTML = formData.value.wechat
    })
    return doc.body.innerHTML
  }
}
const isCustom = ref('0') //   短信模板是否自定义1 是  0 否
//模版选则
const textTemplateChange = val => {
  templateDetail(val).then(res => {
    let text = res.data.content
    originalTemplate.value = text
    isCustom.value = res.data.isCustom //是否是自定义模版
    formData.value.content = replaceText(text, true)
  })
} //会员费到期时间 选中
const reservationDateChange = val => {
  let text = JSON.parse(JSON.stringify(formData.value.content))
  if (text) {
    formData.value.content = replaceText(text, text.indexOf('HYFDQSJ') != '-1')
  }
}
//银行账号选中
const bankAccountChange = val => {
  if (formData.value.content) {
    formData.value.content = replaceText(
      formData.value.content,
      formData.value.content.indexOf('YHZH') != '-1'
    )
  }
}
const sendBtnLoading = ref(false)
const originalTemplate = ref('') //最原始短信版本
//发送短信
const sendSMSFn = () => {
  if (!formData.value.textTemplatename) {
    proxy.$modal.msgWarning('请选择模板')
    return false
  }

  const orgParams = [
    {
      name: 'KHMC',
      fieldName: 'customerName',
      title: '客户名称'
    },
    {
      name: 'HYFDQSJ',
      fieldName: 'expirationDate',
      title: '会员费到期时间'
    },
    {
      name: 'YHZH',
      fieldName: 'bankAccount',
      title: '银行账号'
    },
    {
      name: 'JE',
      fieldName: 'money',
      title: '金额'
    },
    {
      name: 'WX',
      fieldName: 'wechat',
      title: '微信账号'
    }
  ]
  if (isCustom.value == '0') {
    //固定模版
    const formDataNew = JSON.parse(JSON.stringify(formData.value))
    // 提取模板中的所有占位符
    const placeholders = originalTemplate.value.match(
      /KHMC|HYFDQSJ|YHZH|JE|WX/g
    )
    console.log('匹配到字段名：', placeholders)
    // 检查每个占位符对应的字段名在 formDataNew 中是否有值
    const missingFields = orgParams
      .filter(param => placeholders.includes(param.name))
      .filter(param => !formDataNew[param.fieldName])
      .map(param => param.title)

    // 输出缺失字段提示
    if (missingFields.length > 0) {
      proxy.$modal.msgWarning(`${missingFields.join('，')}不能为空`)
      return false
    }
  }
  if (!formData.value.telephone) {
    proxy.$modal.msgWarning('客户电话不能为空')
    return false
  }
  if (!formData.value.content) {
    proxy.$modal.msgWarning('发送预览不能为空')
    return false
  }

  const reg = /^((\+?86)|(\(\+86\)))?((1[0-9])\d{9})$/
  if (!reg.test(formData.value.telephone) && formData.value.telephone != '') {
    proxy.$modal.msgWarning('客户电话请输入正确手机号格式')
    return false
  }
  formData.value.businessId = props.paramData.customerId
  sendBtnLoading.value = true
  sendSms(formData.value)
    .then(res => {
      getList()
      proxy.$modal.msgSuccess('发送短信成功')
    })
    .finally(e => {
      sendBtnLoading.value = false
    })
}
watch(
  () => props.paramData,
  val => {
    if (JSON.stringify(val) != '{}') {
      console.log('短信接收参数：', val)
      formData.value.customerTaxcode = props.paramData.customerTaxcode
      formData.value.customerId = props.paramData.customerId
      formData.value.customerName = props.paramData.customerName
      formData.value.telephone = props.paramData.telVal
      formData.value.expirationDate = props.paramData.expirationDate
        ? props.paramData.expirationDate + ' 00:00:00'
        : ''
      formData.value.wechat = userStore.userInfo.wechat
      getList()
      getTemplateList()
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style lang="scss" scoped>
.callCenterInfos {
  .textMessage-Btn {
    text-align: right;
    margin-bottom: 15px;
  }
}
</style>
